from django.shortcuts import render
from django.http import HttpResponse
import json
from .penbook import PenBook
# Create your views here.


#搜索接口
def search_api_url(request):
    return_info = {'book_info': None}
    return_info = json.dumps(return_info)
    if request.method == 'POST':
        try:
            data_info = request.POST
            keyword = data_info['keyword']
        except KeyError:
            return HttpResponse(return_info)
        else:
            x = PenBook(keyword)
            search_dict = x.searchinfo()
            return HttpResponse(json.dumps(search_dict))
    else:
        return HttpResponse(return_info)


#首页接口
def home_api_url(request):
    return_info = {'book_info':None}
    return_info = json.dumps(return_info)
    if request.method == 'POST':
        try:
            data_info = request.POST
            xx = data_info['homepage']
        except KeyError:
            return HttpResponse(return_info)
        else:
            if xx == "homepage":
                x = PenBook()
                home_dict = x.penhome()
                return HttpResponse(json.dumps(home_dict))
            else:
                return HttpResponse(return_info)
    else:
        return HttpResponse(return_info)



#小说信息接口
def novel_api_url(request):
    return_info = {'book_info': None}
    return_info = json.dumps(return_info)
    if request.method == 'POST':
        try:
            data_info = request.POST
            novel_url = data_info['novel_url']
        except KeyError:
            return HttpResponse(return_info)
        else:
            x = PenBook()
            novel_dict = x.pennovel(novel_url = novel_url)
            return HttpResponse(json.dumps(novel_dict))
    else:
        return HttpResponse(return_info)


def chapter_api_url(request):
    return_info = {'book_info': None}
    return_info = json.dumps(return_info)
    if request.method == 'POST':
        try:
            data_info = request.POST
            chapter_url = data_info['chapter_url']
        except KeyError:
            return HttpResponse(return_info)
        else:
            x = PenBook()
            novel_dict = x.novel_chapter(chapter_url = chapter_url)
            return HttpResponse(json.dumps(novel_dict))
    else:
        return HttpResponse(return_info)